package com.koron.order.linepatrol.nopatrol.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.koron.bean.query.PageQuery;
import com.koron.bean.system.org.OrgBean;
import com.koron.common.core.util.OrgCacheUtils;
import com.koron.order.common.tools.CommonCodeTools;
import com.koron.order.common.tools.OrderCodeEnum;
import com.koron.order.linepatrol.base.bean.po.PatrolPointPo;
import com.koron.order.linepatrol.base.service.PatrolPointService;
import com.koron.order.linepatrol.base.service.PatrolService;
import com.koron.order.linepatrol.nopatrol.bean.dto.LineNoPatrolDTO;
import com.koron.order.linepatrol.nopatrol.bean.po.LineNoPatrol;
import com.koron.order.linepatrol.nopatrol.bean.po.LineNoPatrolPoint;
import com.koron.order.linepatrol.nopatrol.bean.query.LineNoPatrolQuery;
import com.koron.order.linepatrol.nopatrol.bean.vo.LineNoPatrolVO;
import com.koron.order.linepatrol.nopatrol.mapper.LineNoPatrolMapper;
import com.koron.order.linepatrol.nopatrol.service.LineNoPatrolPointService;
import com.koron.order.linepatrol.nopatrol.service.LineNoPatrolService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 不巡视单(LineNoPatrol)表服务实现类
 *
 * @author jzp
 * @since 2022-11-30 11:49:32
 */
@Slf4j
@Service
public class LineNoPatrolServiceImpl implements LineNoPatrolService {

    @Autowired
    private PatrolPointService linePatrolPointService;

    @Autowired
    private LineNoPatrolPointService lineNoPatrolPointService;

    @Autowired
    private PatrolService linePatrolService;

    @Autowired
    OrgCacheUtils orgCacheUtils;

    /**
     * 通过ID查询单条数据
     *
     */
    @Override
    @TaskAnnotation("getById")
    public LineNoPatrolVO getById(SessionFactory factory, String id) {
        LineNoPatrolMapper mapper = factory.getMapper(LineNoPatrolMapper.class);
        return mapper.selectById(id);
    }

    @Override
    @TaskAnnotation("getDtoById")
    public LineNoPatrolDTO getDtoById(SessionFactory factory, String id) {
        LineNoPatrolVO lineNoPatrolVO = getById(factory, id);
        LineNoPatrolDTO lineNoPatrolDTO = BeanUtil.toBean(lineNoPatrolVO, LineNoPatrolDTO.class);
        List<LineNoPatrolPoint> pointList = lineNoPatrolPointService.listByNoPatrolId(factory, id);
        lineNoPatrolDTO.setPointList(pointList);
        return lineNoPatrolDTO;
    }

    /**
     * 查询所有数据
     *
     */
    @Override
    @TaskAnnotation("list")
    public List<LineNoPatrolVO> list(SessionFactory factory, LineNoPatrolQuery query) {
        LineNoPatrolMapper mapper = factory.getMapper(LineNoPatrolMapper.class);
        return mapper.selectList(query);
    }

    @Override
    @TaskAnnotation("page")
    public PageInfo<LineNoPatrolVO> page(SessionFactory factory, PageQuery pageQuery, LineNoPatrolQuery query) {
        pageQuery.unPrefixOrders("lineNoPatrol", Arrays.asList("currNodeCode","currNodeName",
                "currNodeUser"));
        return LineNoPatrolService.super.page(factory, pageQuery, query);
    }

    /**
     * 新增数据
     *
     */
    @Override
    @TaskAnnotation("save")
    public boolean save(SessionFactory factory, LineNoPatrol lineNoPatrol) {
        LineNoPatrolMapper mapper = factory.getMapper(LineNoPatrolMapper.class);
        // 设置工单编号
        if (lineNoPatrol.getStatus() == null) {
            lineNoPatrol.setStatus("0");
        }
        if ("finish".equals(lineNoPatrol.getDataSource()) && "0".equals(lineNoPatrol.getStatus())) {
            // 设置巡视工单的prepare为0，标记为正在完成巡视
            linePatrolService.updatePrepare(factory, lineNoPatrol.getPatrolId(), "0");
        }

        if (StringUtils.isEmpty(lineNoPatrol.getCode())) {
            OrgBean orgBean = orgCacheUtils.getOrgById(lineNoPatrol.getDeptId());
            if(orgBean!=null){
                String simpleEn = orgBean.getPrefix();
                lineNoPatrol.setCode(CommonCodeTools.getOrderCode(OrderCodeEnum.BXS,simpleEn));
            }else {
                lineNoPatrol.setCode(CommonCodeTools.getNormalOrderCode(OrderCodeEnum.BXS));
            }
        }
        return mapper.insertOrUpdate(lineNoPatrol) > 0;
    }

    @Override
    @TaskAnnotation("saveDto")
    public boolean saveDto(SessionFactory factory, LineNoPatrolDTO lineNoPatrolDTO) {
        Assert.notEmpty(lineNoPatrolDTO.getPointList(), "不巡视点不能为空");

        // 设置不巡视点数
        if (lineNoPatrolDTO.getNoPatrolPointTotal() == null) {
            lineNoPatrolDTO.setNoPatrolPointTotal(lineNoPatrolDTO.getPointList().size());
        }
        // 设置巡视点总数
        if (lineNoPatrolDTO.getPointTotal() == null) {
            PatrolPointPo patrolPointPo = new PatrolPointPo();
            patrolPointPo.setPatrolId(lineNoPatrolDTO.getPatrolId());
            List<PatrolPointPo> patrolPointPos = linePatrolPointService.queryList(factory, patrolPointPo);
            lineNoPatrolDTO.setPointTotal(patrolPointPos == null ? 0 : patrolPointPos.size());
        }

        // 保存主表
        boolean b = this.save(factory, lineNoPatrolDTO);
        // 删除并保存不巡视点
        boolean b1 = lineNoPatrolPointService.removeByNoPatrolId(factory, lineNoPatrolDTO.getId());
        lineNoPatrolDTO.getPointList().forEach(e -> e.setNoPatrolId(lineNoPatrolDTO.getId()));
        boolean b2 = lineNoPatrolPointService.saveBatch(factory, lineNoPatrolDTO.getPointList());
        // 如果存在流程，改
        if (StrUtil.isNotEmpty(lineNoPatrolDTO.getCurrNodeCode())) {
            List<String> pointIds = lineNoPatrolDTO.getPointList().stream().map(LineNoPatrolPoint::getPointId).collect(Collectors.toList());
            linePatrolPointService.updateBatchStatus(factory, pointIds, "NO_PATROL", "0");
        }
        return b || b1 || b2;
    }

    @Override
    @TaskAnnotation("submit")
    public boolean submit(SessionFactory factory, LineNoPatrolDTO lineNoPatrolDTO) {
        lineNoPatrolDTO.setStatus("1");
        boolean b = saveDto(factory, lineNoPatrolDTO);
        // 修改巡视点状态为不巡视
        List<String> pointIds = lineNoPatrolDTO.getPointList().stream().map(LineNoPatrolPoint::getPointId).collect(Collectors.toList());
        boolean b1 = linePatrolPointService.updateBatchStatus(factory, pointIds, "NO_PATROL", "1") > 0;
        // 如果是完成巡视过来，标记巡视工单为正在完成巡视
        if ("finish".equals(lineNoPatrolDTO.getDataSource())) {
            linePatrolService.updatePrepare(factory, lineNoPatrolDTO.getPatrolId(), "1");
        }
        return b || b1;
    }

    @Override
    @TaskAnnotation("end")
    public boolean end(SessionFactory factory, LineNoPatrolDTO lineNoPatrolDTO) {
        lineNoPatrolDTO.setStatus("2");
        boolean b = saveDto(factory, lineNoPatrolDTO);
        // 修改巡视点状态为不巡视
        List<String> pointIds = lineNoPatrolDTO.getPointList().stream().map(LineNoPatrolPoint::getPointId).collect(Collectors.toList());
        boolean b1 =  linePatrolPointService.updateBatchStatus(factory, pointIds, "NO_PATROL", "2") > 0;
        // 如果是完成巡视过来
        if ("finish".equals(lineNoPatrolDTO.getDataSource())) {
            // 查询该巡视工单的所有巡视点
            PatrolPointPo patrolPointPo = new PatrolPointPo();
            patrolPointPo.setPatrolId(lineNoPatrolDTO.getPatrolId());
            List<PatrolPointPo> patrolPointPos = linePatrolPointService.queryList(factory, patrolPointPo);
            // 如果所有巡视点都是不巡视，则工单改为不巡视
            if (patrolPointPos.stream().filter(e -> "".equals(e.getStatus())).count() == patrolPointPos.size()) {
                linePatrolService.updateStatus(factory, lineNoPatrolDTO.getPatrolId(), "NO_PATROL");
            } else {
                // 否则该为已巡视
                linePatrolService.updateStatus(factory, lineNoPatrolDTO.getPatrolId(), "END_PATROL");
            }

        }
        return b || b1;
    }

    /**
     * 修改数据
     *
     */
    @Override
    @TaskAnnotation("update")
    public boolean update(SessionFactory factory, LineNoPatrol lineNoPatrol) {
        LineNoPatrolMapper mapper = factory.getMapper(LineNoPatrolMapper.class);
        return mapper.update(lineNoPatrol) > 0;
    }

    @Override
    @TaskAnnotation("updateStatus")
    public boolean updateStatus(SessionFactory factory, String id, String status) {
        LineNoPatrol lineNoPatrol = new LineNoPatrol();
        lineNoPatrol.setId(id);
        lineNoPatrol.setStatus(status);
        return update(factory, lineNoPatrol);
    }

    /**
     * 通过主键删除数据
     *
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        LineNoPatrolMapper mapper = factory.getMapper(LineNoPatrolMapper.class);
        LineNoPatrolVO lineNoPatrolVO = getById(factory, id);
        linePatrolService.updateStatus(factory, lineNoPatrolVO.getPatrolId(), "NO_PATROL");
        return mapper.hidden(id) > 0;
    }
}
